<?php
namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use app\service\TopviewApiService;
use app\constant\ProductBackgroundStatus;

/**
 * 阶段2：轮询背景生成任务（template_id=background_v2, status=1），成功后落库结果
 */
class CheckProductBackgroundResults extends Command
{
    protected function configure()
    {
        $this->setName('check:product-background-results')
            ->setDescription('轮询背景生成任务结果');
    }

    protected function execute(Input $input, Output $output)
    {
        $api = new TopviewApiService();
        $output->writeln('开始检查背景生成结果...');

        $tasks = Db::name('product_anyshoot_tasks')
            ->where('template_id', 'background_v2')
            ->where('status', ProductBackgroundStatus::GENERATING)
            ->where('task_id', '<>', '')
            ->order('id', 'asc')
            ->limit(50)
            ->select();

        foreach ($tasks as $task) {
            try {
                $output->writeln("检查背景生成: {$task['task_id']}");
                $res = $api->queryProductBackgroundTask($task['task_id']);
                $status = $res['status'] ?? '';
                if ($status === 'success') {
                    $images = $res['anyfitImages'] ?? [];
                    Db::name('product_anyshoot_tasks')
                        ->where('id', $task['id'])
                        ->update([
                            'status' => ProductBackgroundStatus::SUCCESS,
                            'result_images' => json_encode($images, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                            'update_time' => date('Y-m-d H:i:s')
                        ]);
                    $output->writeln("背景生成完成: {$task['task_id']}");
                } elseif ($status === 'failed') {
                    Db::name('product_anyshoot_tasks')
                        ->where('id', $task['id'])
                        ->update([
                            'status' => ProductBackgroundStatus::FAILED,
                            'update_time' => date('Y-m-d H:i:s')
                        ]);
                    $output->writeln("背景生成失败: {$task['task_id']}");
                }
            } catch (\Exception $e) {
                $output->writeln('处理失败: ' . $e->getMessage());
            }
        }

        $output->writeln('检查完成');
        return 0;
    }
}


